from docx import Document
import pandas as pd
import os
from openpyxl import Workbook
from openpyxl.drawing.image import Image
import re

# 自然排序键生成函数
def natural_sort_key(filename):
    return [
        int(part) if part.isdigit() else part.lower()
        for part in re.split(r'(\d+)', filename)
    ]

# 读取word文档中的表格和图片，将内容按照格式输出到指定excel
def read_tables_and_images_from_word(doc_path,filename):
    try:
        # 打开Word文档
        doc = Document(doc_path)

        # 定义一个字典来存储提取的信息
        extracted_data = {}

        # 遍历文档中的所有表格
        for table_index, table in enumerate(doc.tables):
            if(table_index == 0):#只获取第一个表格即可
                for row_index, row in enumerate(table.rows):
                    row_data = [cell.text.strip() for cell in row.cells]
                    extracted_data['序号']=re.split(r'(\d+)', filename)[1]
                    if row_index == 0:
                        extracted_data['姓名'] = row_data[1]
                        extracted_data['性别'] = row_data[3]
                    elif row_index == 1:
                        extracted_data['学历'] = row_data[1]
                        extracted_data['出生年月'] = row_data[3]
                    elif row_index == 2:
                        extracted_data['身份证*'] = row_data[1]
                    elif row_index == 3:
                        extracted_data['专业'] = row_data[1]
                        extracted_data['参加工作时间'] = row_data[4]
                    elif row_index == 4:
                        extracted_data['申请层级'] = row_data[1]
                        extracted_data['擅长领域'] = row_data[4]
                    elif row_index == 5:
                        extracted_data['工作单位*'] = row_data[1]
                        extracted_data['职务职称'] = row_data[4]
                    elif row_index == 6:
                        extracted_data['现从事岗位'] = row_data[4]
                    elif row_index == 7:
                        extracted_data['手机号*'] = row_data[1]
                        extracted_data['E-mail'] = row_data[4]
                    elif row_index == 8:
                        extracted_data['教育背景'] = row_data[1]
                    elif row_index == 9:
                        extracted_data['工作经历'] = row_data[1]
                    print(f"Row {row_index + 1}: {row_data}")
                print("\n")

        # 提取文档中的图片
        images = []
        if any("image" in rel.target_ref for rel in doc.part.rels.values()):
            for rel in doc.part.rels.values():
                if "image" in rel.target_ref:
                    image_part = rel.target_part
                    image_bytes = image_part.blob
                    image_path = os.path.join(os.path.dirname(doc_path), f"{extracted_data['身份证*']}.png")
                    with open(image_path, "wb") as f:
                        f.write(image_bytes)
                    images.append(image_path)
        else:
            extracted_data['图片路径'] = ''
            print(f"No images found in document {doc_path}")
        # 假设每个文档只有一张图片，存储第一个图片路径
        if images:
            extracted_data['图片路径'] = images[0]
        else:
            extracted_data['图片路径'] = ''

        return extracted_data
    except Exception as e:
        print(f"Error processing document {doc_path}: {e}")
        return None

def export_to_excel_with_images(data_list, excel_path):
    try:
        # 创建一个新的工作簿
        wb = Workbook()
        ws = wb.active

        # 写入表头，增加一列用于图片
        headers = ['序号', '姓名', '性别', '学历', '出生年月', '身份证*', '专业', '参加工作时间', '申请层级', '擅长领域', '工作单位*', '职务职称', '现从事岗位', '手机号*', 'E-mail', '教育背景', '工作经历', '图片']
        ws.append(headers)

        # 写入数据
        img_row = 2  # 从第二行开始插入数据
        for data in data_list:
            row = [data.get(header, '') for header in headers[:-1]]  # 不包括最后一列'图片'
            ws.append(row)

            # 插入图片
            if '图片路径' in data and data['图片路径']:
                img_path = data['图片路径']
                if os.path.exists(img_path):
                    img = Image(img_path)
                    img.width = 100
                    img.height = 150
                    ws.add_image(img, f'R{img_row}')  # 图片放在'R'列
                else:
                    print(f"Image not found: {img_path}")
                img_row += 1  # 移动到下一行插入下一张图片
            else:
                img_row += 1  # 移动到下一行插入下一张图片
                print(f"No image path found for data: {data}")

        # 保存工作簿
        wb.save(excel_path)
    except Exception as e:
        print(f"Error exporting to Excel {excel_path}: {e}")


def process_documents_in_folder(folder_path, excel_path):
    # 存储所有提取的信息
    all_data = []

    # 遍历文件夹中的所有文件并排序
    filenames = [filename for filename in os.listdir(folder_path) if filename.endswith('.docx')]
    filenames.sort(key=natural_sort_key)  # 按文件名中的数字升序排序

    for filename in filenames:
        doc_path = os.path.join(folder_path, filename)
        print(f"Processing document: {doc_path}")

        # 读取表格数据并提取特定信息
        extracted_data = read_tables_and_images_from_word(doc_path,filename)

        # 如果提取的数据不为空，则添加到列表中
        #if extracted_data is not None:
            #all_data.append(extracted_data)
            #print(f"Extracted data: {extracted_data}\n")

    # 导出所有提取的信息到Excel文件
    #export_to_excel_with_images(all_data, excel_path)
    print(f"Exported all data to: {excel_path}")

# 示例用法
folder_path = 'F:\检查员个人申请表\初级85'  # 替换为你的文档文件夹路径
excel_path = 'F:\\test专家数据抽取.xlsx'  # 替换为你的输出Excel文件路径

# 处理文件夹中的所有文档
process_documents_in_folder(folder_path, excel_path)
